﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Bazookabird.Common;
using Bazookabird.Common.Plugin;
using Bazookabird.Wpf.Builds;
using Bazookabird.Wpf.Queries;
using Caliburn.Micro;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;

namespace Bazookabird.Wpf 
{
    using System.ComponentModel.Composition;

    // TODO: http://blogs.microsoft.co.il/blogs/shair/archive/2010/02/11/tfs-api-part-20-bye-teamfoundationserver-and-welcome-tfsteamprojectcollection.aspx
    // TODO: http://blogs.microsoft.co.il/blogs/shair/archive/2010/11/17/tfs-api-part-30-working-with-queries.aspx
    // TODO: http://blogs.microsoft.co.il/blogs/shair/archive/2010/11/18/tfs-api-part-31-working-with-queries-part-2.aspx

    [Export(typeof(IShell))]
    public class ShellViewModel : Conductor<object>.Collection.OneActive, IShell
    {
        public ShellViewModel()
        {
            Timer = new Timer {Interval = 60000};
            Timer.Tick += RefreshPanels;
            Timer.Start();

            ActivationProcessed += ShellViewModelActivationProcessed;
        }

        protected override void OnActivate()
        {
            base.OnActivate();
            DisplayName = "Bazookabird - Simple TFS Dashboard";
        }

        void ShellViewModelActivationProcessed(object sender, ActivationProcessedEventArgs e) { } 

        private IWindowManager _windowManager;
        [Import]
        public IWindowManager WindowManager
        {
            get { return _windowManager; }
            set
            {
                _windowManager = value;
                NotifyOfPropertyChange(() => WindowManager);
            }
        }

        private BuildListViewModel _buildListViewModel;
        private QueryListViewModel _queryListViewModel;

        private IEnumerable<IBuildHandler> _buildHandlers;
        [ImportMany(typeof(IBuildHandler))]
        public IEnumerable<IBuildHandler> BuildHandlers
        {
            get { return _buildHandlers; }
            set
            {
                _buildHandlers = value;
                NotifyOfPropertyChange(() => BuildHandlers);
            }
        }

        private IEnumerable<IQueryHandler> _queryHandlers;
        [ImportMany(typeof(IQueryHandler))]
        public IEnumerable<IQueryHandler> QueryHandlers
        {
            get { return _queryHandlers; }
            set
            {
                _queryHandlers = value;
                NotifyOfPropertyChange(() => QueryHandlers);
            }
        }

        private TfsTeamProjectCollection _projectCollection;
        public TfsTeamProjectCollection ProjectCollection
        {
            get { return _projectCollection; }
            set
            {
                _projectCollection = value;
                NotifyOfPropertyChange(() => ProjectCollection);
            }
        }

        private ProjectInfo _projectInfo;
        public ProjectInfo ProjectInfo
        {
            get { return _projectInfo; }
            set
            {
                _projectInfo = value;
                ResetViews();

                NotifyOfPropertyChange(() => ProjectInfo);
                NotifyOfPropertyChange(() => ProjectStatus);
                NotifyOfPropertyChange(() => CanOpenBuildList);
                NotifyOfPropertyChange(() => CanOpenQueryList);
            }
        }

        public Timer Timer { get; set; }

        private void ResetViews()
        {
            CloseBuildListView();
            CloseQueryListView();
        }

        private void CloseBuildListView()
        {
            
            if (_buildListViewModel != null)
            {
                DeactivateItem(_buildListViewModel, false);
                _buildListViewModel = null;
            }
        }

        private void CloseQueryListView()
        {
            if (_queryListViewModel != null)
            {
                DeactivateItem(_queryListViewModel, false);
                _queryListViewModel = null;
            }
        }

        public string ProjectStatus
        {
            get
            {
                if (_projectInfo != null && _projectCollection != null)
                {
                    return string.Format("{0}>{1}", _projectCollection.Name, _projectInfo.Name);
                }
                return string.Empty;
            }
        }

        public void Connect()
        {
            using(var domainPicker = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false))
            {
                var result = domainPicker.ShowDialog();
                if (result != DialogResult.OK) return;
                
                UpdateProjectInfo(domainPicker);
            }
        }

        public bool CanOpenBuildList
        {
            get { return ProjectInfo != null; }
        }

        public void OpenBuildList()
        {
            WindowManager.ShowDialog(_buildListViewModel ?? (_buildListViewModel = CreateBuildListViewModel()));
        }

        private BuildListViewModel CreateBuildListViewModel()
        {
            return new BuildListViewModel(this, ProjectCollection, _projectInfo.Name, BuildHandlers);
        }

        public void OpenQueryList()
        {
            WindowManager.ShowDialog(_queryListViewModel ?? (_queryListViewModel = CreateQuerylistViewModel()));
        }

        public bool CanOpenQueryList
        {
            get { return ProjectInfo != null; }
        }

        public void AddPluginToCurrentScreen(IBazookabirdPlugin plugin)
        {
            ActivateItem(plugin);
            NotifyOfPropertyChange(() => CanCloseCurrentItem);
        }

        public bool CanCloseCurrentItem
        {
            get { return Items.Any(); }
        }

        public void CloseCurrentItem()
        {
            DeactivateItem(ActiveItem, true);
            NotifyOfPropertyChange(() => CanCloseCurrentItem);
        }

        private QueryListViewModel CreateQuerylistViewModel()
        {
            return new QueryListViewModel(this, ProjectCollection, _projectInfo.Name, QueryHandlers);
        }

        private void UpdateProjectInfo(TeamProjectPicker domainPicker)
        {
            ProjectCollection = domainPicker.SelectedTeamProjectCollection;
            ProjectInfo = domainPicker.SelectedProjects.First();
        }

        void RefreshPanels(object sender, EventArgs e)
        {
            if (Items == null) return;
            foreach (IRefresh refreshable in Items)
            {
                refreshable.Refresh();
            }
        }
    }
}
